<template>
  <div class="tag-management-container">
    <div class="page-header">
      <h1>标签管理</h1>
      <p>管理系统中的标签，用于分类和标识项目、任务等。支持按模块分类管理。</p>
    </div>

    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>标签列表</span>
          <el-button type="primary" @click="handleAddTag">添加标签</el-button>
        </div>
      </template>

      <!-- 筛选工具栏 -->
      <div class="filter-toolbar">
        <el-select
          v-model="filterModuleType"
          placeholder="选择模块"
          clearable
          style="width: 160px"
          @change="handleFilterChange"
        >
          <el-option label="全部模块" value="all" />
          <el-option
            v-for="module in moduleTypes"
            :key="module.value"
            :label="module.label"
            :value="module.value"
          />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索标签名称或描述"
          clearable
          style="width: 250px"
          @clear="handleFilterChange"
          @keyup.enter="handleFilterChange"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-checkbox v-model="includeSystem" @change="handleFilterChange">
          显示系统标签
        </el-checkbox>
      </div>

      <el-table 
        :data="tagList" 
        v-loading="loading" 
        border 
        stripe
        table-layout="auto"
        fit
        style="width: 100%"
      >
        <el-table-column prop="name" label="标签名称" min-width="150" align="left">
          <template #default="{ row }">
            <el-tag 
              :color="row.color" 
              style="color: white; border: none;"
              :style="{ maxWidth: '100%' }"
              class="tag-name"
            >
              {{ row.name }}
              <el-tag v-if="row.is_system" type="info" size="small" style="margin-left: 4px">
                系统
              </el-tag>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module_type" label="所属模块" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.module_type" :type="getModuleTagType(row.module_type)" size="small">
              {{ getModuleLabel(row.module_type) }}
            </el-tag>
            <span v-else class="text-muted">通用</span>
          </template>
        </el-table-column>
        <el-table-column 
          prop="description" 
          label="描述" 
          min-width="200" 
          align="left"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.description">{{ row.description }}</span>
            <span v-else class="text-muted">无描述</span>
          </template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" min-width="100" align="center">
          <template #default="{ row }">
            <div class="color-display">
              <div class="color-block" :style="{ backgroundColor: row.color }"></div>
              <span class="color-value">{{ row.color }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="usage_count" label="使用次数" min-width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.usage_count || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column 
          label="创建时间" 
          min-width="160"
          align="center"
          v-if="!isMobile"
        >
          <template #default="{ row }">
            <span v-if="row.created_at">{{ formatDate(row.created_at) }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column 
          label="更新时间" 
          min-width="160"
          align="center"
          v-if="!isMobile"
        >
          <template #default="{ row }">
            <span v-if="row.updated_at">{{ formatDate(row.updated_at) }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 标签表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑标签' : '添加标签'"
      :width="isMobile ? '90%' : '500px'"
      :before-close="handleClose"
    >
      <el-form
        ref="tagFormRef"
        :model="tagForm"
        :rules="tagRules"
        label-width="100px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="所属模块" prop="module_type">
          <el-select
            v-model="tagForm.module_type"
            placeholder="选择模块（可选，留空为通用标签）"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="module in moduleTypes"
              :key="module.value"
              :label="module.label"
              :value="module.value"
            />
          </el-select>
          <div class="form-tip">留空表示通用标签，可在所有模块中使用</div>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="tagForm.color" :predefine="predefineColors" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="tagForm.description"
            type="textarea"
            placeholder="请输入标签描述"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSaveTag"
            :loading="saving"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { getTags, getTagsWithPagination, createTag, updateTag, deleteTag } from '@/api/tags'
import type { Tag, TagListParams } from '@/types/tag'
import { MODULE_TYPES, getModuleLabel } from '@/utils/moduleTypes'

// 响应式数据
const tagList = ref<Tag[]>([])
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEditing = ref(false)
const currentPage = ref(1)
const pageSize = ref(50)
const total = ref(0)
const tagFormRef = ref<FormInstance>()

// 筛选条件
const filterModuleType = ref<string>('all')
const searchKeyword = ref('')
const includeSystem = ref(true)

// 模块类型配置
const moduleTypes = MODULE_TYPES

// 预定义颜色列表
const predefineColors = [
  '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399',
  '#1890FF', '#52C41A', '#FAAD14', '#F5222D', '#722ED1',
  '#13C2C2', '#EB2F96', '#FA8C16', '#A0D911', '#2F54EB'
]

// 响应式设计
const isMobile = computed(() => {
  return window.innerWidth < 768
})

// 标签表单
const tagForm = reactive({
  id: '',
  name: '',
  description: '',
  color: '#409EFF',
  module_type: null as string | null
})

// 表单验证规则
const tagRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  color: [
    { required: true, message: '请选择标签颜色', trigger: 'change' }
  ]
})

// 获取标签列表
const fetchTags = async () => {
  try {
    loading.value = true
    
    const params: TagListParams = {
      page: currentPage.value,
      page_size: pageSize.value,
      include_system: includeSystem.value
    }
    
    if (filterModuleType.value && filterModuleType.value !== 'all') {
      params.module_type = filterModuleType.value
    }
    
    if (searchKeyword.value) {
      params.search = searchKeyword.value
    }
    
    // 使用带分页信息的API
    const result = await getTagsWithPagination(params)
    
    tagList.value = result.items || []
    total.value = result.total || 0
  } catch (error) {
    console.error('获取标签列表失败:', error)
    ElMessage.error('获取标签列表失败')
    tagList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 筛选变化处理
const handleFilterChange = () => {
  currentPage.value = 1
  fetchTags()
}

// 获取模块标签类型
const getModuleTagType = (moduleType: string): string => {
  const module = moduleTypes.find(m => m.value === moduleType)
  if (!module) return ''
  // 将color转换为element plus的tag type
  const colorMap: Record<string, string> = {
    'blue': 'primary',
    'green': 'success',
    'orange': 'warning',
    'red': 'danger',
    'purple': '',
    'geekblue': 'info',
    'magenta': '',
    'volcano': '',
    'gold': '',
    'cyan': 'info'
  }
  return colorMap[module.color] || ''
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchTags()
}

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchTags()
}

// 处理添加标签
const handleAddTag = () => {
  isEditing.value = false
  Object.assign(tagForm, {
    id: '',
    name: '',
    description: '',
    color: '#409EFF',
    module_type: filterModuleType.value && filterModuleType.value !== 'all' ? filterModuleType.value : null
  })
  dialogVisible.value = true
}

// 处理编辑标签
const handleEdit = (row: Tag) => {
  isEditing.value = true
  Object.assign(tagForm, {
    id: row.id,
    name: row.name,
    description: row.description || '',
    color: row.color,
    module_type: row.module_type || null
  })
  dialogVisible.value = true
}

// 处理对话框关闭
const handleClose = () => {
  dialogVisible.value = false
  // 重置表单
  if (tagFormRef.value) {
    tagFormRef.value.resetFields()
  }
}

// 处理保存标签
const handleSaveTag = async () => {
  if (!tagFormRef.value) return
  
  await tagFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        if (isEditing.value) {
          // 更新标签
          await updateTag(tagForm.id, {
            name: tagForm.name,
            color: tagForm.color,
            description: tagForm.description || undefined,
            module_type: tagForm.module_type || null
          })
          ElMessage.success('标签更新成功')
        } else {
          // 创建标签
          await createTag({
            name: tagForm.name,
            color: tagForm.color,
            description: tagForm.description || undefined,
            module_type: tagForm.module_type || null
          })
          ElMessage.success('标签添加成功')
        }
        dialogVisible.value = false
        fetchTags()
        saving.value = false
      } catch (error) {
        console.error('保存标签失败:', error)
        ElMessage.error('保存标签失败')
        saving.value = false
      }
    }
  })
}

// 处理删除标签
const handleDelete = async (row: Tag) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除标签 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API删除标签
    await deleteTag(row.id)
    ElMessage.success('标签删除成功')
    fetchTags()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除标签失败:', error)
      ElMessage.error('删除标签失败')
    }
  }
}

// 监听窗口大小变化
const handleResize = () => {
  // 响应式逻辑会在computed属性中自动更新
}

// 初始化
onMounted(() => {
  fetchTags()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.tag-management-container {
  padding: 16px;
  background: #f0f2f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 16px;
}

.page-header h1 {
  font-size: 22px;
  margin: 0 0 6px 0;
  font-weight: 500;
}

.page-header p {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.main-card {
  margin-bottom: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
}

.el-table {
  flex: 1;
}

/* 优化表格列宽度，使其更加紧凑 */
:deep(.el-table__header-wrapper th) {
  font-weight: 500;
  padding: 12px 10px;
}

:deep(.el-table__body-wrapper td) {
  padding: 10px;
}

.color-display {
  display: flex;
  align-items: center;
  gap: 6px;
}

.color-block {
  width: 18px;
  height: 18px;
  border-radius: 3px;
  border: 1px solid #ddd;
}

.color-value {
  font-family: monospace;
  font-size: 11px;
}

.text-muted {
  color: #999;
  font-size: 13px;
}

.filter-toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  flex-wrap: wrap;
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  padding: 12px 0;
}

.tag-name {
  font-size: 13px;
  padding: 4px 8px;
  height: auto;
  white-space: normal;
  word-break: break-word;
}

/* 优化响应式布局 */
@media (max-width: 768px) {
  .tag-management-container {
    padding: 12px;
  }
  
  .card-header {
    padding: 10px 16px;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .card-header .el-button {
    width: 100%;
  }
}

/* 确保按钮样式一致 */
:deep(.el-button) {
  font-size: 14px;
}

:deep(.el-button--link) {
  padding: 4px 10px;
}
</style>